#include<iostream>
#include<thread>
#include<mutex>
#include<atomic>
#include<chrono>
#include<random>
#include<cstring>
using namespace std;

std::mutex mtx;//互斥锁，用于控制共享资源的访问
std::atomic<bool> channelBusy(false);//表示信道是否忙
std::atomic<bool> collisionDetected(false);//表示是否检测到冲突

void propagationDelay(int milliseconds)//模拟信道传播延迟
{
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

void hostSendData(const std::string& hostName,int data)//主机发送数据的函数
{
    while(true)
	{
        if(!channelBusy)//检测信道是否空闲
		{
            mtx.lock();
            cout << hostName << " Sending data: " << data << endl;
            channelBusy=true;//占用信道
            mtx.unlock();            
            propagationDelay(100);//模拟数据传输时间

            if(collisionDetected)//检测冲突
			{
                mtx.lock();
                cout << hostName << " Conflict detected, stop sending and wait for retry..." << endl;
                mtx.unlock();

                //随机退避时间
                std::random_device rd;
                std::mt19937 gen(rd());
                std::uniform_int_distribution<> dis(100, 500);
                int backoffTime=dis(gen);
                propagationDelay(backoffTime);
                collisionDetected=false;//重置冲突标志
                continue;//重试发送
            }

            //数据发送成功
            mtx.lock();
            cout << hostName << " Data sent successfully: " << data << endl;
            channelBusy=false;//释放信道
            mtx.unlock();
            break;
        }
		else propagationDelay(10);//信道繁忙，等待
    }
}

void simulateCollision()//模拟冲突检测
{
    propagationDelay(50);//模拟冲突发生的时间
    collisionDetected=true;//设置冲突标志
}

int main()
{
    //创建两个线程模拟两个主机
    std::thread hostA(hostSendData,"HostA",123);
    std::thread hostB(hostSendData,"HostB",456);

    //模拟冲突
    std::thread collision(simulateCollision);

    //等待线程完成
    hostA.join();
    hostB.join();
    collision.join();
    return 0;
}